<template>
  <div
    class="scan-input-box"
    :class="disabled ? 'scan-input-box-disabeld' : ''"
  >
    <el-input
      ref="codeInput"
      v-model="code"
      :clearable="true"
      style="width: 400px"
      :disabled="disabled"
      placeholder="请扫码或输入条码"
      @keyup.enter.native="sacn"
      @input="(e) => (code = validSe(e))"
    >
      <template #prepend>产品条码</template>
    </el-input>
    <el-dialog
      title="扫描从码"
      width="30%"
      v-model="dialogSubCodeVisible"
      @close="handleSubClose"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <div class="scan-dialog">
        <div class="info">
          <div class="name">
            产品名称：{{ productDetail && productDetail.commonName }}产品
          </div>
        </div>
        <el-input
          ref="subCodeRef"
          @keyup.enter.native="sacnSubCode"
          @input="(e) => (inputSubCode = validSe(e))"
          placeholder="请扫描从码"
          v-model="inputSubCode"
          clearable
        ></el-input>
      </div>
      <template #footer class="dialog-footer">
        <el-button @click="handleSubClose">关闭</el-button>
      </template>
    </el-dialog>
    <el-dialog
      title="扫描主码"
      width="30%"
      v-model="dialogMainCodeVisible"
      @close="handleMainClose"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <div class="scan-dialog">
        <el-input
          ref="mainCodeRef"
          @keyup.enter.native="sacnMainCode"
          @input="(e) => (inputMainCode = validSe(e))"
          placeholder="请扫描主码"
          v-model="inputMainCode"
          clearable
        ></el-input>
      </div>
      <template #footer class="dialog-footer">
        <el-button @click="handleMainClose">关闭</el-button>
      </template>
    </el-dialog>
    <SelectScanProduct
      v-if="selectScanProductInfo.visible"
      v-model:show-dialog="selectScanProductInfo.visible"
      :sacnData="selectScanProductInfo.sacnData"
      :fieldList="selectScanProductInfo.fieldList"
      :highlightRow="true"
      :checkBox="false"
      @callback="selectScanProductCallBack"
    ></SelectScanProduct>
  </div>
</template>

<script setup name="ScanInputBox">
import {
  scanUpdateInventoryDetail,
  scanUpdateSubInventoryDetail,
} from '@/api/stock'
const { proxy } = getCurrentInstance()
const props = defineProps({
  query: {
    type: Object,
    default: undefined,
  },
  api: {
    type: Function,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  isSysGroup: {
    type: Boolean,
    default: true,
  },
  selectObj: {
    type: Object,
    default: function () {
      return {}
    },
  },
  inventoryType: {
    type: String,
    default: '',
  },
})
/*
    .0盘点明细中找到(滚动+标记)
    .1已盘点（提示）
    .2已被其他子盘点单盘点(提示)
    .3在其他仓库找到(提示)
    .4不在零星盘点范围中(提示)
    .5产品码,在当前库存中没找到(提示)
    .6在当前库存，返回明细信息 （滚动+标记）
    .7在其他货位找到(提示)
    .11匹配到了多个主码，需要输入从码
    .12匹配到了多个从码，需要输入主码
    .13在当前仓库，但不在本次盘点范围(提示)
    .15全库都没找到，解析出来的(加一条)
    */
const dialogSubCodeVisible = ref(false)
const dialogMainCodeVisible = ref(false)
const inputSubCode = ref('')
const inputMainCode = ref('')
const productDetail = ref(undefined)
const code = ref('')
const selectScanProductInfo = ref({
  visible: false,
  sacnData: [],
  fieldList: [
    { label: '货位编码', value: 'locationNo' },
    { label: '供应商', value: 'supplierName' },
    {
      label: '单价',
      value: 'price',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '库存数量',
      value: 'stockQty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    { label: '入库批次号', value: 'storeBatchNumber' },
  ],
})
function sacn() {
  if (!props.query.locationNo) {
    proxy.$message({
      message: '请扫描或选择或输入货位码',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    code.value = ''
    return
  }
  if (!code.value) {
    proxy.$message({
      message: '请扫描二维码',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }

  const params = {
    ...props.query,
    code: proxy.$fn.setTrim(code.value),
  }
  props
    .api(params)
    .then((res) => {
      if (res && res.success) {
        const scanState = res.data.flag
        switch (scanState) {
          case 0:
            return scanResult(res.data.data, scanState)
            break
          case 1:
            return handleClose('已盘点')
            break
          case 2:
            return handleClose('已被其他子盘点单盘点')
            break
          case 3:
            // return handleClose("在其他仓库找到");
            let depotName = res.data.data.map((item) => item.depotName)
            return handleClose(`在【${depotName}】仓库找到`)
            break
          case 4:
            return handleClose('不在零星盘点范围中')
            break
          case 5:
            return handleClose('产品码，在当前库存中没找到')
            break
          case 6:
            return scanResult(res.data.data, scanState)
            break
          case 7:
            // return handleClose("在其他仓库找到");
            let locationNo = res.data.data.map((item) => item.locationNo)
            return handleClose(`在【${locationNo}】货位找到`)
            break
          case 8:
            selectScanProductInfo.value.visible = true
            selectScanProductInfo.value.sacnData = res.data.data
            return
            break
          case 11:
            return scanProgressSub()
            break
          case 12:
            return scanProgressMain()
            break
          case 13:
            return handleClose('在当前仓库，但不在本次盘点范围')
            break
          case 15:
            return scanResult(res.data.data, scanState)
            break
        }
      } else {
        code.value = ''
      }
    })
    .catch((err) => {
      code.value = ''
    })
}
function sacnSubCode() {
  if (code.value) inputMainCode.value = code.value
  const params = {
    ...props.query,
    subCode: proxy.$fn.setTrim(inputSubCode.value),
    mainCode: proxy.$fn.setTrim(inputMainCode.value),
  }
  props
    .api(params)
    .then((res) => {
      if (res && res.success) {
        const flag = res.data.flag
        if (flag > -1) {
          switch (flag) {
            case 0:
              return scanResult(res.data.data, flag)
              break
            case 1:
              return handleClose('已盘点')
              break
            case 2:
              handleClose('已被其他子盘点单盘点')
              break
            case 3:
              // return handleClose("在其他仓库找到");
              let depotName = res.data.data.map((item) => item.depotName)
              return handleClose(`在【${depotName}】仓库找到`)
              break
            case 4:
              return handleClose('不在零星盘点范围中')
              break
            case 5:
              return handleClose('产品码，在当前库存中没找到')
              break
            case 6:
              return scanResult(res.data.data, flag)
              break
            case 7:
              let locationNo = res.data.data.map((item) => item.locationNo)
              return handleClose(`在【${locationNo}】货位找到`)
            case 8:
              selectScanProductInfo.value.visible = true
              selectScanProductInfo.value.sacnData = res.data.data
              return
              break
            case 13:
              handleClose('在当前仓库，但不在本次盘点范围')
              break
            case 15:
              return scanResult(res.data.data, flag)
              break
          }
        } else {
          proxy.$message({
            message: `扫码报错！`,
            type: 'warning',
            duration: 3500,
            showClose: true,
          })
        }
      } else {
        inputSubCode.value = ''
      }
    })
    .catch((err) => {
      inputSubCode.value = ''
    })
}
function sacnMainCode() {
  const params = {
    ...props.query,
    subCode: proxy.$fn.setTrim(code.value),
    mainCode: proxy.$fn.setTrim(inputMainCode.value),
  }
  props
    .api(params)
    .then((res) => {
      if (res && res.success) {
        const flag = res.data.flag
        if (flag > -1) {
          switch (flag) {
            case 0:
              return scanResult(res.data.data, flag)
              break
            case 1:
              return handleClose('已盘点')
              break
            case 2:
              return handleClose('已被其他子盘点单盘点')
              break
            case 3:
              // return handleClose("在其他仓库找到");
              let depotName = res.data.data.map((item) => item.depotName)
              return handleClose(`在【${depotName}】仓库找到`)
              break
            case 4:
              return handleClose('不在零星盘点范围中')
              break
            case 5:
              return handleClose('产品码，在当前库存中没找到')
              break
            case 6:
              return scanResult(res.data.data, flag)
              break
            case 7:
              let locationNo = res.data.data.map((item) => item.locationNo)
              return handleClose(`在【${locationNo}】货位找到`)
            case 8:
              selectScanProductInfo.value.visible = true
              selectScanProductInfo.value.sacnData = res.data.data
              return
              break
            case 13:
              handleClose('在当前仓库，但不在本次盘点范围')
              break
            case 15:
              return scanResult(res.data.data, flag)
              break
          }
        } else {
          proxy.$message({
            message: `扫码报错！`,
            type: 'warning',
            duration: 3500,
            showClose: true,
          })
        }
      } else {
        inputMainCode.value = ''
      }
    })
    .catch((err) => {
      inputMainCode.value = ''
    })
}
function selectScanProductCallBack(data) {
  let api =
    props.inventoryType === 'main'
      ? scanUpdateInventoryDetail
      : props.inventoryType === 'sub'
      ? scanUpdateSubInventoryDetail
      : undefined
  api(data).then((res) => {
    if (res && res.success) {
      data.calcQty = data.unitConvertCoefficient
      data.qty = proxy.$fn.accDiv(data.calcQty, data.unitConvertCoefficient)
      data.largeUnitQty = parseInt(data.calcQty / data.unitConvertCoefficient)
      data.smallUnitQty = parseInt(data.calcQty % data.unitConvertCoefficient)
      scanResult(data, 0)
    }
  })
}
function scanResult(data, flag) {
  if (flag !== 6) {
    if (!data.supplierId) {
      data.supplierId = -2
    }
    data.currentScanData = true
    if (props.isSysGroup) {
      let key = ''
      for (let item in props.selectObj) {
        key = key + data[item] + '&'
      }
      data.key = key
    } else {
      // 一物一码带上码校验
      if (data.codeType === 2 || data.codeType === 3 || data.codeType === 4) {
        data.key =
          data.productId +
          '&' +
          data.batchNumber +
          '&' +
          data.validityDate +
          '&' +
          data.productionDate +
          '&' +
          data.price +
          '&' +
          data.qrCode +
          '&' +
          data.uniqueCode +
          '&' +
          data.factorySubCode +
          '&' +
          data.factoryMainCode
      } else {
        data.key =
          data.productId +
          '&' +
          data.batchNumber +
          '&' +
          data.validityDate +
          '&' +
          data.productionDate +
          '&' +
          data.price
      }
    }
  }
  if (flag === 6) {
    proxy.$message({
      message: `扫产品码成功`,
      type: 'success',
      duration: 3500,
      showClose: true,
    })
  } else {
    proxy.$message({
      message: `扫码成功`,
      type: 'success',
      duration: 3500,
      showClose: true,
    })
  }
  proxy.$emit('callback', { data: data, flag: flag })
  handleClose()
}

function scanProgressSub(data) {
  dialogSubCodeVisible.value = true
  productDetail.value = { ...data }
  let timer = setTimeout(() => {
    proxy.$refs.subCodeRef.focus()
    clearTimeout(timer)
  }, 100)
}
function scanProgressMain() {
  dialogMainCodeVisible.value = true
  let timer = setTimeout(() => {
    proxy.$refs.mainCodeRef.focus()
    clearTimeout(timer)
  }, 100)
}
function handleClose(msg = '') {
  inputSubCode.value = undefined
  inputMainCode.value = undefined
  code.value = undefined
  dialogSubCodeVisible.value = false
  dialogMainCodeVisible.value = false
  if (msg) {
    proxy.$message({
      message: msg,
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
  }
}
function handleSubClose() {
  inputSubCode.value = undefined
  code.value = undefined
  dialogSubCodeVisible.value = false
}
function handleMainClose() {
  inputMainCode.value = undefined
  code.value = undefined
  dialogMainCodeVisible.value = false
}
</script>

<style scoped></style>
